package com.wdullaer.datetimepickerexampleohos;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Checkbox;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.RadioContainer;
import ohos.agp.components.Text;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;

import com.wdullaer.materialdatetimepicker.Utils;
import com.wdullaer.materialdatetimepicker.common.Log;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import com.wdullaer.materialdatetimepicker.time.Timepoint;

import java.io.IOException;
import java.util.Calendar;

/**
 * A simple {@link Fraction} subclass.
 */
public class TimePickerFraction extends Fraction implements TimePickerDialog.OnTimeSetListener {

    private Text timeTextView;
    private Checkbox mode24Hours;
    private Checkbox modeDarkTime;
    private Checkbox modeCustomAccentTime;
    private Checkbox vibrateTime;
    private Checkbox dismissTime;
    private Checkbox titleTime;
    private Checkbox enableSeconds;
    private Checkbox limitSelectableTimes;
    private Checkbox disableSpecificTimes;
    private Checkbox showVersion2;
    private TimePickerDialog tpd;

    TimePickerDialog.Type calendarType;
    Font font;

    public TimePickerFraction() {
        // Required empty public constructor
    }

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        Component component = scatter.parse(ResourceTable.Layout_timepicker_layout, container, false);

        // Find our Component instances
        timeTextView = (Text) component.findComponentById(ResourceTable.Id_time_textview);
        Button timeButton = (Button) component.findComponentById(ResourceTable.Id_time_button);
        mode24Hours = (Checkbox) component.findComponentById(ResourceTable.Id_mode_24_hours);
        modeDarkTime = (Checkbox) component.findComponentById(ResourceTable.Id_mode_dark_time);
        modeCustomAccentTime = (Checkbox) component.findComponentById(ResourceTable.Id_mode_custom_accent_time);
        vibrateTime = (Checkbox) component.findComponentById(ResourceTable.Id_vibrate_time);
        dismissTime = (Checkbox) component.findComponentById(ResourceTable.Id_dismiss_time);
        titleTime = (Checkbox) component.findComponentById(ResourceTable.Id_title_time);
        enableSeconds = (Checkbox) component.findComponentById(ResourceTable.Id_enable_seconds);
        limitSelectableTimes = (Checkbox) component.findComponentById(ResourceTable.Id_limit_times);
        disableSpecificTimes = (Checkbox) component.findComponentById(ResourceTable.Id_disable_times);
        showVersion2 = (Checkbox) component.findComponentById(ResourceTable.Id_show_version_2);

        try {
            font = Utils.getFont(getFractionAbility(), "resources/rawfile/fonts/" + "IRANSansMobile(FaNum).ttf");
        } catch (IOException e) {
            e.getMessage();
        }
        final int[] selectedIndex = {0};
        RadioContainer radioContainer = (RadioContainer) component.findComponentById(ResourceTable.Id_calendar_type_radio_container);
        radioContainer.mark(0);
        radioContainer.setMarkChangedListener(new RadioContainer.CheckedStateChangedListener() {
            @Override
            public void onCheckedChanged(RadioContainer radioContainer, int index) { // TODO 待调试验证
                selectedIndex[0] = index;
            }
        });
        // Show a timepicker when the timeButton is clicked
        timeButton.setClickedListener(c -> {
            Calendar now = Calendar.getInstance();
            if (selectedIndex[0] == 0) {
                calendarType = TimePickerDialog.Type.JALALI;
            } else {
                calendarType = TimePickerDialog.Type.GREGORIAN;
            }
            /*
            It is recommended to always create a new instance whenever you need to show a Dialog.
            The sample app is reusing them because it is useful when looking for regressions
            during testing
             */
            if (tpd == null) {
                tpd = TimePickerDialog.newInstance(
                    calendarType,
                    c.getContext(),
                    TimePickerFraction.this,
                    now.get(Calendar.HOUR_OF_DAY),
                    now.get(Calendar.MINUTE),
                    mode24Hours.isChecked()
                );
            } else {
                tpd.initialize(
                    calendarType,
                    TimePickerFraction.this,
                    now.get(Calendar.HOUR_OF_DAY),
                    now.get(Calendar.MINUTE),
                    now.get(Calendar.SECOND),
                    mode24Hours.isChecked()
                );
            }
            switch (calendarType) {
                case GREGORIAN:
                    tpd.setFont(null);
                    break;

                case JALALI:
                    tpd.setFont(font);
            }
            tpd.setThemeDark(modeDarkTime.isChecked());
            tpd.vibrate(vibrateTime.isChecked());
            tpd.dismissOnPause(dismissTime.isChecked());
            tpd.enableSeconds(enableSeconds.isChecked());
            tpd.setVersion(showVersion2.isChecked() ? TimePickerDialog.Version.VERSION_2 : TimePickerDialog.Version.VERSION_1);
            if (modeCustomAccentTime.isChecked()) {
                tpd.setAccentColor(Color.getIntColor("#9C27B0"));
            }
            if (titleTime.isChecked()) {
                switch (calendarType) {
                    case GREGORIAN:
                        tpd.setTitle("DATEPICKER TITLE");
                        break;
                    case JALALI:
                        tpd.setTitle("عنوان انتخابگر تاریخ");
                        break;
                }
            }
            if (limitSelectableTimes.isChecked()) {
                if (enableSeconds.isChecked()) {
                    tpd.setTimeInterval(3, 5, 10);
                } else {
                    tpd.setTimeInterval(3, 5, 60);
                }
            }
            if (disableSpecificTimes.isChecked()) {
                Timepoint[] disabledTimes = {
                    new Timepoint(10),
                    new Timepoint(10, 30),
                    new Timepoint(11),
                    new Timepoint(12, 30)
                };
                tpd.setDisabledTimes(disabledTimes);
            }
            tpd.setOnCancelListener(dialogInterface -> {
                Log.d("TimePicker", "Dialog was cancelled");
                tpd = null;
            });
            tpd.show();

        });

        return component;
    }

    @Override
    protected void onStop() {
        super.onStop();
        tpd = null;
    }

    @Override
    protected void onBackground() {
        super.onBackground();
        if (tpd != null) {
            tpd.onBackground(tpd);
            tpd = null;
        }
    }

    @Override
    protected void onActive() {
        super.onActive();
        if (tpd != null) tpd.setOnTimeSetListener(this);
    }

    @Override
    public void onTimeSet(TimePickerDialog dialog, int hourOfDay, int minute, int second) {
        String hourString = hourOfDay < 10 ? "0" + hourOfDay : "" + hourOfDay;
        String minuteString = minute < 10 ? "0" + minute : "" + minute;
        String secondString = second < 10 ? "0" + second : "" + second;
        String time = "You picked the following time: " + hourString + "h" + minuteString + "m" + secondString + "s";
        timeTextView.setText(time);
        tpd = null;
    }
}
